#!/bin/sh

csid=$1
oraHome=$2
ouser=$3

if [ "$#" -ne 3 ]; then
 echo "This script needs 3 input parameter"
 echo "usage: OracleASMDBRewind.sh <cloned database name> <Oracle Home path> <Oracle User> "
 echo " For example: OracleASMDBRewind.sh clonedb /home/oracle/app/oracle/product/11.2.0/dbhome_1 oracle"
fi

BASEDIR=$(dirname $0)
echo $BASEDIR
cd $BASEDIR

ORACLE_HOME=$oraHome
export ORACLE_HOME
ORACLE_SID=$csid
export ORACLE_SID
PATH=$ORACLE_HOME/bin:$PATH
export PATH

if [ -z "$csid" ]; then
   echo "need SID to proceed"
   exit 1
fi

if [ ! -d $ORACLE_HOME ]; then
   echo "could not find ORACLE_HOME "
   exit 1
fi

scriptsRoot=${LB_ROOT}
if [ -z "$scriptsRoot" ];then
    echo "missing env LB_ROOT"
    exit 1
fi

CSID=`echo $csid | tr [a-z] [A-Z]`
echo $CSID

su $ouser -c "$ORACLE_HOME/bin/sqlplus -s / as sysdba << EOF
set heading off
set feedback off
shutdown immediate;
exit;
EOF
"

su $ouser -c "srvctl stop database -d $csid"
if [ -z "$isrestore" ] || [ "$isrestore" != "true" ]; then
su $ouser -c "srvctl remove database -d $csid -f"

dgid=`echo $CSID | tr [A-Z] [a-z]`
if [ -d "/opt/howlink/linkBackup/touch/$dgid" ]; then
    rm -rf /opt/howlink/linkBackup/touch/$dgid
fi
if [ -d "/opt/howlink/linkBackup/touch/$CSID" ]; then
    rm -rf /opt/howlink/linkBackup/touch/$CSID
fi

if [ "$notnsupdate" != "true" ]; then
towner=`ls -ld $tnsadmindir | awk '{print $3}'`
# cleanup tns entry
csid1=$csid"1"
su $towner -c "${scriptsRoot}/oracle/oracleclone/cleanupTNSNames.sh $csid $ORACLE_HOME 6 $tnsadmindir"
su $towner -c "${scriptsRoot}/oracle/oracleclone/cleanupTNSNames.sh $csid1 $ORACLE_HOME 7 $tnsadmindir"
fi

# cleanup oratab
${scriptsRoot}/oracle/oracleclone/cleanupOratab.sh $csid
${scriptsRoot}/oracle/oracleclone/cleanupOratab.sh $csid1

echo "cleanup init$csid.ora"
rm -f $ORACLE_HOME/dbs/init$csid.ora
rm -f $ORACLE_HOME/dbs/init$CSID.ora
rm -f $ORACLE_HOME/dbs/orapw$csid
rm -f $ORACLE_HOME/dbs/orapw$CSID
rm -f $ORACLE_HOME/../../init$csid.ora
rm -f $ORACLE_HOME/../../init$CSID.ora

if [ -d "$ORACLE_HOME/../../admin/$CSID" ]; then
    rm -rf $ORACLE_HOME/../../admin/$CSID
fi
if [ -d "$ORACLE_HOME/../../admin/$csid" ]; then
    rm -rf $ORACLE_HOME/../../admin/$csid
fi
if [ -d "$ORACLE_HOME/../../diag/rdbms/$csid" ]; then
    rm -rf $ORACLE_HOME/../../diag/rdbms/$csid
fi
if [ -d "$ORACLE_HOME/../../diag/rdbms/$CSID" ]; then
    rm -rf $ORACLE_HOME/../../diag/rdbms/$CSID
fi
if [ -d "$ORACLE_HOME/log/diag/rdbms/$csid" ]; then
    rm -rf $ORACLE_HOME/log/diag/rdbms/$csid
fi
if [ -d "$ORACLE_HOME/log/diag/rdbms/$CSID" ]; then
    rm -rf $ORACLE_HOME/log/diag/rdbms/$CSID
fi
if [ -d "$ORACLE_HOME/../../../diag/rdbms/$csid" ]; then
    rm -rf $ORACLE_HOME/../../../diag/rdbms/$csid
fi
if [ -d "$ORACLE_HOME/../../../diag/rdbms/$CSID" ]; then
    rm -rf $ORACLE_HOME/../../../diag/rdbms/$CSID
fi

rm -f setdb_$csid*
#rm -f dbrecover_$csid*
#rm -f openDBlog_$csid*
rm -f nid_$csid*

rm -f ${scriptsRoot}/oracle/oracleclone/setdb_$csid*
fi

echo "done rewind"

